package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YYGHException;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.repository.HosptialRepository;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HosptialService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/*==========================================
      时 间:   2022-03-07
      讲 师:   刘  辉
      描 述:   尚硅谷教学团队
 ==========================================*/
@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private HosptialRepository  hosptialRepository;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private HosptialService hosptialService;

    @Override
    public void saveSchedule(Map<String, Object> paramMap) {

        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(paramMap), Schedule.class);
        Schedule  mongoSchedule= scheduleRepository.findByHoscodeAndDepcodeAndHosScheduleId(schedule.getHoscode(),schedule.getDepcode(),schedule.getHosScheduleId());
        if(mongoSchedule == null){//添加
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        }else{ //更新操作
            schedule.setCreateTime(mongoSchedule.getCreateTime());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(mongoSchedule.getIsDeleted());
            schedule.setId(mongoSchedule.getId());
            scheduleRepository.save(schedule);
        }

    }

    @Override
    public Page getSchedulePage(Map<String, Object> paramMap) {
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(paramMap), Schedule.class);
        int page=Integer.parseInt((String)paramMap.get("page"));
        int limit=Integer.parseInt((String)paramMap.get("limit"));
        Pageable pageable = PageRequest.of(page-1,limit, Sort.by(Sort.Direction.ASC,"createTime"));
        Example example=Example.of(schedule);
        return scheduleRepository.findAll(example,pageable);
    }

    @Override
    public void remove(Map<String, Object> paramMap) {
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(paramMap), Schedule.class);
        String hoscode = schedule.getHoscode();
        String hosScheduleId = schedule.getHosScheduleId();
        Schedule schedule1=scheduleRepository.findByHoscodeAndHosScheduleId(hoscode,hosScheduleId);
        if(schedule1 == null){
            throw new YYGHException(20001,"没有对应的排班信息");
        }else{
            scheduleRepository.deleteById(schedule1.getId());
        }

    }

    @Override
    public Map<String, Object> getSchedulePageByCondition(Integer page, Integer limit, String hoscode, String depcode) {
        Map<String, Object> map = new HashMap<String, Object>();

        /**
         * 需要三个参数：
         *  1.aggregation:聚合对象，封装的是聚合的条件
         *  2.inputType: 输入类型的字节码，与操作的集合对应的pojo类的字节码
         *  3.outputType: 输出类型的字节码，使用哪个pojo类封装聚合后的结果
         */
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                Aggregation.sort(Sort.Direction.ASC,"workDate"),
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)

        );
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> mappedResults = aggregate.getMappedResults();

        for (BookingScheduleRuleVo mappedResult : mappedResults) {
            Date workDate = mappedResult.getWorkDate();
            mappedResult.setDayOfWeek(getDayOfWeek(new DateTime(workDate)));
        }

        Aggregation aggregation1 = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate"));

        AggregationResults<BookingScheduleRuleVo> totalAggregate = mongoTemplate.aggregate(aggregation1, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggregate.getMappedResults().size();

        //获取医院名称
        Hospital hospital = hosptialRepository.findByHoscode(hoscode);
        map.put("hosname",hospital.getHosname());
        map.put("list",mappedResults);
        map.put("total",total);

        return map;
    }

    @Override
    public List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate) {
        List<Schedule> list =scheduleRepository.findByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,new DateTime(workDate).toDate());
        //把得到list集合遍历，向设置其他值：医院名称、科室名称、日期对应星期
        list.stream().forEach(item->{
            this.packageSchedule(item);
        });

        return list;
    }


    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        Hospital hospital = hosptialRepository.findByHoscode(hoscode);
        if(hospital == null){
            throw new YYGHException(20001,"不存在该医院");
        }
        BookingRule bookingRule = hospital.getBookingRule();


        com.baomidou.mybatisplus.extension.plugins.pagination.Page datelistPage= this.dateList(page,limit,bookingRule);
        List<Date> records = datelistPage.getRecords();

        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(records);
        
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                Aggregation.sort(Sort.Direction.ASC, "workDate"));
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> mappedResults = aggregate.getMappedResults();


        //2012-02-10
        Map<Date, BookingScheduleRuleVo> map = mappedResults.stream().collect(Collectors.toMap(BookingScheduleRuleVo->BookingScheduleRuleVo.getWorkDate(), BookingScheduleRuleVo -> BookingScheduleRuleVo));

        List<BookingScheduleRuleVo> bookingScheduleRuleVoList=new ArrayList<BookingScheduleRuleVo>();

        for (int i = 0; i < records.size(); i++) {
            int len = records.size();
            Date date = records.get(i);
            BookingScheduleRuleVo bookingScheduleRuleVo = map.get(date);

            if(bookingScheduleRuleVo== null){
                bookingScheduleRuleVo=new BookingScheduleRuleVo();
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
                bookingScheduleRuleVo.setReservedNumber(0);
            }

            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期为周几
            bookingScheduleRuleVo.setDayOfWeek(this.getDayOfWeek(new DateTime(date)));

            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if(i == len-1 && page == datelistPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            if(i == 0 && page == 1) {
                DateTime dateTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if(dateTime.isBeforeNow()){
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }


        Map<String,Object> result = new HashMap<String,Object>();

        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", datelistPage.getTotal());

        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称

        baseMap.put("hosname", hosptialService.getHospitalDetailByHoscode(hoscode).getHosname());
        //科室
        Department department =departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }

    @Override
    public List<Schedule> findScheduleList(String hoscode, String depcode, String workDate) {
        return scheduleRepository.findByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,new DateTime(workDate).toDate());
    }

    @Override
    public Schedule getScheduleInfoById(String id) {
        Schedule schedule = scheduleRepository.findById(id).get();
        schedule.getParam().put("dayOfWeek", this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        schedule.getParam().put("hosname",hosptialRepository.findByHoscode(schedule.getHoscode()).getHosname());
        schedule.getParam().put("depname",departmentRepository.findByHoscodeAndDepcode(schedule.getHoscode(),schedule.getDepcode()).getDepname());
        return schedule;
    }

    @Override
    public ScheduleOrderVo getScheduleOrderInfoById(String scheduleId) {
        ScheduleOrderVo orderVo = new ScheduleOrderVo();
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        BeanUtils.copyProperties(schedule,orderVo);
        Hospital hospital = hosptialRepository.findByHoscode(schedule.getHoscode());
        orderVo.setHosname(hospital.getHosname());
        orderVo.setDepname(departmentRepository.findByHoscodeAndDepcode(schedule.getHoscode(),schedule.getDepcode()).getDepname());
        orderVo.setReserveDate(schedule.getWorkDate());
        orderVo.setReserveTime(schedule.getWorkTime());
        String quitTime = hospital.getBookingRule().getQuitTime();


        //退号时间：
        //退号截止天数（如：就诊前一天为-1，当天为0）
        BookingRule bookingRule = hospital.getBookingRule();
        int quitDay = bookingRule.getQuitDay();

        //年月日：时分秒的时间
        orderVo.setQuitTime(this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime()).toDate());

//        //预约开始时间
//        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
//        scheduleOrderVo.setStartTime(startTime.toDate());
//
//        //预约截止时间
//        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
//        scheduleOrderVo.setEndTime(endTime.toDate());
//
//        //当天停止挂号时间
//        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
//        scheduleOrderVo.setStopTime(stopTime.toDate());
        return orderVo;
    }

    @Override
    public void update(Schedule schedule) {
        //mogn
        scheduleRepository.save(schedule);
    }

    @Override
    public Schedule getScheduleInfoByScheduleId(String scheduleId) {
        return scheduleRepository.findByHosScheduleId(scheduleId);
    }

    private com.baomidou.mybatisplus.extension.plugins.pagination.Page dateList(Integer page, Integer limit, BookingRule bookingRule) {
        //每天的放号时间
        String releaseTime = bookingRule.getReleaseTime();
        //今天的放号时间
        DateTime dateTime = this.getDateTime(new Date(), releaseTime);

        Integer cycle = bookingRule.getCycle();
        //如果此时此刻已经超过了医院规定的当天的放号时间，就把预约周期加1
        if(dateTime.isBeforeNow()){
            cycle=cycle+1;
        }

        List<Date> totalDateList=new ArrayList<Date>();
        for(int i=0;i<cycle;i++){
            DateTime dateTime1 = new DateTime().plusDays(i);
            totalDateList.add(new DateTime(dateTime1.toString("yyyy-MM-dd")).toDate());
        }

        int start=(page-1)*limit;
        int end=start+limit;
        if(end >= totalDateList.size()){
            end =totalDateList.size();
        }


        List<Date> currentPageDateList=new ArrayList<Date>();


        for(int i=start;i<end;i++){
            currentPageDateList.add(totalDateList.get(i));
        }


        com.baomidou.mybatisplus.extension.plugins.pagination.Page pageResult=  new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page,limit,totalDateList.size());
        pageResult.setRecords(currentPageDateList);
        return pageResult;
    }


    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }


    private void packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname",hosptialRepository.findByHoscode(schedule.getHoscode()).getHosname());
        //设置科室名称
        schedule.getParam().put("depname",departmentRepository.findByHoscodeAndDepcode(schedule.getHoscode(),schedule.getDepcode()).getDepname());
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
    }

    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }
}
